package com.jnxx.task.WxUtils;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jnxx.task.domain.OkrStaff;
import com.jnxx.task.service.IDepartmentService;
import com.jnxx.task.service.IOkrStaffService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class WeChatUtils {

    @Autowired
    public RedisTemplate redisTemplate;
    private RestTemplate restTemplate = new RestTemplate();
    private ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private IOkrStaffService staffService;

    @Autowired
    private IDepartmentService departmentService;


    public List<Map<String, Object>> getDepartmentListAndUserDetails(String token) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=" + token;
        ValueOperations<String, Object> ops = redisTemplate.opsForValue();
        List<Map<String, Object>> departmentList;
        try {
            if(redisTemplate.hasKey("departmentList")) {
                departmentList = (List<Map<String, Object>>) ops.get("departmentList");
            } else {
                String result = restTemplate.getForObject(url, String.class);
                Map<String, Object> resultMap = objectMapper.readValue(result, new TypeReference<Map<String, Object>>() {});
                departmentList = (List<Map<String, Object>>) resultMap.get("department");
                System.out.println(departmentList);
                for (Map<String, Object> department : departmentList) {
                    // 添加部门信息
//                    Department departmentTem = new Department();
//                    departmentTem.setName(department.get("name").toString());
//                    departmentTem.setOrdered(department.get("order").toString());
//                    departmentTem.setParentid(department.get("parentid").toString());
//                    departmentTem.setLeader(department.get("department_leader").toString());
//                    Object id = department.get("id");
//                    if (id instanceof Integer){
//                        Integer departmentIdInt = (Integer) id;
//                        Long departmentId = Long.valueOf(departmentIdInt);
//                        departmentTem.setId(departmentId);
//                    }
//                    StringBuffer departmentIds = new StringBuffer();
//                    if (department.get("department_leader") instanceof ArrayList){
//                        ArrayList<String> list = (ArrayList<String>) department.get("department_leader");
//                        if (list != null){
//                            for (String learder : list) {
//                                departmentIds.append(learder);
//                            }
//                        }
//                    }
//                    departmentTem.setLeader(departmentIds.toString());
//                    departmentService.add(departmentTem);
                    String departmentId = String.valueOf(department.get("id"));
                    Map<String, Object> departmentUsers = getUserDetailsByDepartmentId(token, departmentId);
                    department.put("users", departmentUsers);
                }
                ops.set("departmentList", departmentList, 1, TimeUnit.DAYS);
            }
            return departmentList;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }

    private Map<String, Object> getUserDetailsByDepartmentId(String token, String departmentId) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token=" + token + "&department_id=" + departmentId;
        Map<String, Object> usersInDepartment = new HashMap<>();
        try {
            String result = restTemplate.getForObject(url, String.class);
            Map<String, Object> resultMap = objectMapper.readValue(result, new TypeReference<Map<String, Object>>() {});
            List<Map<String, Object>> userList = (List<Map<String, Object>>) resultMap.get("userlist");
            System.out.println(userList);
            ValueOperations<String, Object> ops = redisTemplate.opsForValue();
            for (Map<String, Object> user : userList) {
                // 添加员工信息
                OkrStaff staff = new OkrStaff();
                staff.setUserId(user.get("userid").toString());
                staff.setName(user.get("name").toString());
                StringBuffer departmentIds = new StringBuffer();
                if (user.get("department") instanceof ArrayList){
                    ArrayList<Integer> list = (ArrayList<Integer>) user.get("department");
                    if (list != null){
                        for (Integer integer : list) {
                            departmentIds.append(integer).append(",");
                        }
                        try {
                            departmentIds.deleteCharAt(departmentIds.length() -1);
                        } catch (Exception e){
                            System.err.println("添加错误，信息为" + e.getMessage());
                        }
                    }
                }
                staff.setDepartmentId(departmentIds.toString());
                OkrStaff staffTmp = staffService.findByUserId(staff.getUserId());

                if (staffTmp == null){
                    staffService.add(staff);
                }

//                if (!redisTemplate.hasKey("user:" + user.get("userid"))) {
//                    ops.set("user:" + user.get("userid"), user, 1, TimeUnit.DAYS);
//                }
                usersInDepartment.put(user.get("userid").toString(), user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return usersInDepartment;
    }
}

